package com.groupbuying.customer.pojo;

import com.groupbuying.customer.utils.RedisUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("deprecation")
public class SessionContext {

	private static Logger log = LoggerFactory.getLogger(SessionContext.class);

	@Autowired
    private RedisUtils redisUtils;

	private static SessionContext instance;
    private Map<String, Session> sessionMap;

    private SessionContext(){
        sessionMap = new HashMap<String, Session>();
    }

    public static SessionContext getInstance(){
        if(instance == null){
            instance = new SessionContext();
        }
        return instance;
    }

    public synchronized void addSession(Session session){
    	log.debug("新增session : " + session.getId());
        if(session != null){
        	session.setTimeout(-1);
           sessionMap.put((String)session.getId(), session);
        }
    }

    public synchronized void delSession(Session session){
        if(session != null){
            sessionMap.remove(session.getId());
        }
    }

    public synchronized Session getSession(String sessionId){
        if(sessionId == null)
            return null;
        return getRedisSession(sessionId);
    }

	/**
     * session存放到redis
     * @param session
     * @param sessionId
     */
    public void setRedisSession(Session session,String sessionId){
//    	JedisPool pool = RedisAPIUtil.getPool();
//		Jedis jedis = null;
		try {
            if(session != null){

                redisUtils.setKey(sessionId, session,30*24 * 60 * 60);
                //jedis.expire(sessionId.getBytes(), 30*24 * 60 * 60);
            }
		} catch (Exception e) {
			//pool.returnBrokenResource(jedis);
			e.printStackTrace();
		}
    }

    /**
     * 从redis里面获取session
     * @param sessionId
     * @return
     */
    public Session getRedisSession(String sessionId){
    	Session s = null;
		try {
		    //sessionId = "RedisLoginUuid_" + sessionId;
				s = (Session) redisUtils.getValue(sessionId);
				if(s != null){
					//jedis.expire(sessionId.getBytes(), 24 * 60 * 60);
					redisUtils.setExpire(sessionId, 30*24 * 60 * 60);
				}
		} catch (Exception e) {
			//pool.returnBrokenResource(jedis);
			e.printStackTrace();
		}
		return s;
    }
}
